import axios from 'axios'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.baseURL = 'http://localhost:8888/'
axios.defaults.timeout = 5000000;
axios.defaults.headers['x-requested-with'] = 'XMLHttpRequest';

// request拦截器
axios.interceptors.request.use(
  (config) => {
    return config;
  },
  error => Promise.error(error),
);

axios.interceptors.response.use(
  async (response) => {
    console.log(response)
    if (response.status === 200) {
      return Promise.resolve(response);
    }
    return Promise.reject(response);
  },
  // 服务器状态码不是200的情况
  error => Promise.reject(error),
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
// eslint-disable-next-line no-shadow
export function get(url, params, config) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params,
        ...config,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
// eslint-disable-next-line no-shadow
export function post(url, params, config, exportExcel) {
  return new Promise((resolve, reject) => {
    // 确保请求头中包含 'Content-Type': 'application/json'
    const headers = {
      'Content-Type': 'application/json;charset=utf-8'
    };

    axios
      .post(url, params, { ...config, headers })
      // .post(url, params, config)
      .then((res) => {
        if (exportExcel) {
          resolve(res);
          return false;
        }
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

